namespace Digitalmes.Application.Mes;

/// <summary>
/// 工位信息表服务接口
/// </summary>
[ApiExplorerSettings(GroupName = "mes")]
public sealed class MdStationService : IDynamicWebApiService
{
    private readonly SugarRepository<MdStation> _thisRepository;

    public MdStationService(SugarRepository<MdStation> thisRepository)
    {
        _thisRepository = thisRepository;
    }

    /// <summary>
    /// 查询所有——分页
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<PageResult<MdStationDto>> GetPagesAsync(PageParam param)
    {
        var query = await _thisRepository.AsQueryable()
            .OrderBy(m => m.Sort)
            .ToPageAsync(param.Page, param.Limit);
        return query.Adapt<PageResult<MdStationDto>>();
    }

    /// <summary>
    /// 根据主键查询
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<PageResult<MdStationDto>> GetByLineAsync(MdStationParam param)
    {
        var model = await _thisRepository.AsQueryable()
            .Where(s => s.LineId == param.LineId)
            .OrderBy(m => m.Sort)
            .ToPageAsync(param.Page, param.Limit);
        return model.Adapt<PageResult<MdStationDto>>();
    }

    /// <summary>
    /// 根据主键查询
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<MdStationDto> GetAsync(long id)
    {
        var model = await _thisRepository.AsQueryable()
            .Includes(s => s.Line)
            .FirstAsync(s => s.Id == id);
        if (model is null)
        {
            Oops.ThrowBah(ErrCode.E4004);
        }

        var dto = model!.Adapt<MdStationDto>();
        dto.LineName = model!.Line?.LineName;
        return dto;
    }

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<bool> AddAsync(MdStationDto model) 
    {
        if (await _thisRepository.IsAnyAsync(s => s.OpCode == model.OpCode && s.LineId == model.LineId))
        {
            Oops.ThrowBah(ErrCode.E4001);
        }

        int count = await _thisRepository.CountAsync(s => s.LineId == model.LineId);
        model.Sort = count + 1;
        return await _thisRepository.InsertAsync(model.Adapt<MdStation>());
    }

    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<bool> ModifyAsync(MdStationDto model)
    {
        if (await _thisRepository.IsAnyAsync(s => s.OpCode == model.OpCode && s.LineId == model.LineId && s.Id != model.Id))
        {
            Oops.ThrowBah(ErrCode.E4001);
        }

        var item = model.Adapt<MdStation>();
        return await _thisRepository.UpdateAsync(item, s => new { s.OpName, s.Attr, s.Owner, s.Classify, s.UpdateTime, s.UpdateUser });
    }

    /// <summary>
    /// 删除,支持批量
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpDelete]
    public async Task<bool> DeleteAsync([FromBody] long id)
    {
        // 删除项后所有的项重新排序
        var item = await _thisRepository.GetByIdAsync(id);
        if (item is null)
        {
            return true;
        }

        // 重新排序删除项下方的数据
        var downItems = await _thisRepository.GetListAsync(s => s.LineId == item.LineId && s.Sort > item.Sort);
        if (downItems.Any())
        {
            downItems.ForEach(s =>
            {
                s.Sort--;
            });
            await _thisRepository.UpdateAsync(downItems, s => new { s.Sort });
        }

        await _thisRepository.DeleteByIdAsync(id);

        return true;
    }


    /// <summary>
    /// 向上排序
    /// </summary>
    /// <returns></returns>
    [HttpPut]
    public async Task UpSortAsync(SortParam param)
    {
        // 判断是否为第一个
        var item = await _thisRepository.GetByIdAsync(param.Id);
        if (item.Sort == 1)
        {
            return;
        }

        // 此项与上一项 Pos 交换顺序
        List<MdStation> updateItems = new(2)
        {
            item,
        };

        var upItem = await _thisRepository.GetFirstAsync(s => s.LineId == item.LineId && s.Sort == item.Sort - 1);
        if (upItem != null)
        {
            upItem.Sort++;
            updateItems.Add(upItem);
        }

        item.Sort--;
        await _thisRepository.UpdateAsync(updateItems, s => new { s.Sort });
    }

    /// <summary>
    /// 向下排序
    /// </summary>
    /// <returns></returns>
    [HttpPut]
    public async Task DownSortAsync(SortParam param)
    {
        // 判断是否为最后一个
        var item = await _thisRepository.GetByIdAsync(param.Id);
        var downItem = await _thisRepository.GetFirstAsync(s => s.LineId == item.LineId && s.Sort == item.Sort + 1);
        if (downItem == null)
        {
            return;
        }

        // 此项与下一项 Pos 交换顺序
        downItem.Sort--;
        item.Sort++;
        await _thisRepository.AsUpdateable(new[] { downItem, item }).UpdateColumns(s => new { s.Sort }).ExecuteCommandAsync();
    }
}
